#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils import logutils
import subprocess

logger = logutils.getlogger(__file__)


def execute_command(cmd, func=None):
    s = subprocess.Popen(str(cmd), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    stdout, stderror = s.communicate()
    if func:
        logger.info('****************> {} cmd {} finish <****************'.format(func.__name__, cmd))
    else:
        logger.info('****************> finish <****************')

    if s.returncode != 0:
        errstr = "cmd retcode not 0! retcode={},stroud={},stderror={}".format(s.returncode, stdout, stderror)
        raise Exception(errstr)
    if stderror and len(stderror) > 0:
        errstr = "cmd retcode not 0! retcode={},stroud={},stderror={}".format(s.returncode, stdout, stderror)
        raise Exception(errstr)
    if not stdout:
        errstr = "cmd retcode not 0! retcode={},stroud={},stderror={}".format(s.returncode, stdout, stderror)
        raise Exception(errstr)
    elif len(stdout) == 0:
        errstr = "cmd retcode not 0! retcode={},stroud={},stderror={}".format(s.returncode, stdout, stderror)
        raise Exception(errstr)
    # return str(stdout, encoding="utf-8")
    try:
        return stdout.decode()
    except Exception:
        return stdout.decode('utf-8')
